<template>
  <el-form
      ref="ruleFormRef"
      style="max-width: 100%"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
  >
    <el-form-item label="商品分类编码" prop="code">
      <el-input v-model="ruleForm.code" placeholder="请输入商品分类编码"/>
    </el-form-item>
    <el-form-item label="商品分类名称" prop="name">
      <el-input v-model="ruleForm.name" placeholder="请输入商品分类名称"/>
    </el-form-item>

    <el-form-item label="所属分类" prop="parentId">
        <el-tree-select
            v-model="ruleForm.parentId"
            :data="convertedData"
            check-strictly
            :render-after-expand="false"
        />
    </el-form-item>

    <el-form-item  prop="createDate">
      <el-input v-model="ruleForm.createDate" type="hidden"/>
    </el-form-item>
    <el-form-item  prop="updateDate">
      <el-input v-model="ruleForm.updateDate" type="hidden"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm()">提交</el-button>
      <!--            <el-button @click="resetForm()">重置</el-button>-->
      <el-button @click="emitCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import axios from "axios";
import {onMounted, reactive, ref, watch} from 'vue'
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
import type {Customer} from "@/types/public-xs/Customer.ts";
import {ElMessage} from 'element-plus'
import type {GoodsCategory} from "@/types/basic/goodsCategory.ts";
import type {LocationQueryValue} from "vue-router";
import request from "@/util/request.ts";
const props = defineProps<{
  editId?:number|null
}>();
const emit = defineEmits(['submit-success', 'cancel']);

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: props.editId,
  code:'',
  name: '',
  parentId:'',
  createDate:null,
  updateDate:null,
})



let originalData = ref([])

// 执行转换
async function getCategory() {

  let response = await request.post('basic/goodsCategory/showGoodsCategoryByTree');

  // let response = await axios.post('http://localhost:8084/goodsCategory/showGoodsCategoryByTree');
  originalData.value = response.data.data;
}
await getCategory()

function convertNode(node:any) {
  return {
    value: node.id, // 将 id 转为字符串
    label: node.name,
    children: node.children
        ? node.children.map(child => convertNode(child))
        : [] // 递归处理子节点
  };
}


//自定义验证规则
const validateName :any = async (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入商品分类名字'))
  } else {
    let response = await request.get('basic/goodsCategory/getGoodsCategoryByName',{
      params:{
        name:value
      }
    } );

    // const response = await axios.get("http://localhost:8084/goodsCategory/getGoodsCategoryByName", {
    //   params:{
    //     name:value
    //   }
    // });
    if(props.editId){
      callback()
    }
    if (response.data.code=='200') {
      callback(new Error('商品分类名字已存在'))
    }
    callback()
  }
}

//自定义验证规则
const validateCode :any = async (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入商品分类编码'))
  } else {
    let response = await request.get('basic/goodsCategory/getGoodsCategoryByCode',{
      params:{
        code:value
      }
    } );

    // const response = await axios.get("http://localhost:8084/goodsCategory/getGoodsCategoryByCode", {
    //   params:{
    //     code:value
    //   }
    // });
    if(props.editId){
      callback()
    }
    if (response.data.code=='200') {
      callback(new Error('商品分类编码已存在'))
    }
    callback()
  }
}

const convertedData = originalData.value.map(node => convertNode(node));
console.log(convertedData)

const rules = reactive<FormRules>({
  code: [
    {validator: validateCode, trigger: ['blur', 'change']},
    {required: true, message: '请输入商品分类编码', trigger: ['blur', 'change']},
    {min: 3, max: 15, message: '商品分类编码长度应为3到5个字符', trigger: ['blur', 'change']}
  ],
  name: [
    {validator: validateName, trigger: ['blur', 'change']},
    {required: true, message: '请输入商品分类名称', trigger: ['blur', 'change']},
    {min: 2, max: 50, message: '商品分类名称长度应为2到50个字符', trigger: ['blur', 'change']}
  ],
})


// 重置表单
const resetForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};


// 监听 editId 变化
watch(() => props.editId, (newId) => {
  if (newId) {
    backShow(newId); // 每次 editId 变化时重新获取数据
    ruleForm.id = newId
  } else {
    resetForm(); // 如果没有 editId（例如新增），重置表单
  }
}, { immediate: true }); // immediate: true 确保初次渲染时也会触发


// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {

        const url =ruleForm.id ? 'basic/goodsCategory/modifyGoodsCategory' : 'basic/goodsCategory/addGoodsCategory'
        // const response = await axios.post(url, ruleForm);
        const response = await request.post(url, ruleForm);
        ElMessage.success(ruleForm.id ? '更新商品分类成功' : '新增商品分类成功');
        emit('submit-success')
        resetForm(); // 提交成功后重置表单
        backShow(props.editId)
      } catch (error) {
        ElMessage.error(ruleForm.id ? '更新商品分类失败' : '新增商品分类失败');
      }
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};
//回显
async function backShow(id: number) {
  const response = await request.get('basic/goodsCategory/getGoodsCategoryById', {
    params:{
      id:id
    }
  });
  ruleForm.name =response.data.data.name
  ruleForm.code = response.data.data.code
  ruleForm.parentId =response.data.data.parentId
  ruleForm.createDate = response.data.data.createDate
  ruleForm.updateDate = response.data.data.updateDate
}


// 取消操作
const emitCancel = () => {
  emit('cancel'); // 通知父组件取消
};
if(ruleForm.id){
  backShow(props.editId)
}
</script>


<style scoped>
.demo-ruleForm {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 隐藏交易金额输入框的加减按钮 */
.el-input input[type="number"]::-webkit-inner-spin-button,
.el-input input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.el-input input[type="number"] {
  -moz-appearance: textfield; /* Firefox */
}
</style>
